package org.jaaksi.androidforflutterdemo

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.FragmentManager
import io.flutter.embedding.android.FlutterFragment

class TestFlutterFragment : AppCompatActivity() {
  companion object {
    private const val TAG_FLUTTER_FRAGMENT = "flutter_fragment"
  }

  private var flutterFragment: FlutterFragment? = null

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    initFragment()
  }

  // 加载flutter fragment
  private fun initFragment() {
    val fragmentManager: FragmentManager = supportFragmentManager

    // Attempt to find an existing FlutterFragment, in case this is not the
    // first time that onCreate() was run.
    flutterFragment = fragmentManager
      .findFragmentByTag(TAG_FLUTTER_FRAGMENT) as FlutterFragment?

    // Create and attach a FlutterFragment if one does not exist.
    if (null == flutterFragment) {
      var newFlutterFragment =
        FlutterFragment.withCachedEngine(home_page_engine_id).build<FlutterFragment>()
      flutterFragment = newFlutterFragment
      fragmentManager
        .beginTransaction()
        .replace(
          android.R.id.content,
          newFlutterFragment,
          TAG_FLUTTER_FRAGMENT
        )
        .commit()
    }
  }
}